<template>
  <view class="admin-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <text>邻里管家信息管理</text>
    </view>

    <!-- 操作栏：搜索+筛选+新增 -->
    <view class="action-bar">
      <view class="search-filter">
        <input
          v-model="searchQuery"
          placeholder="搜索姓名/电话"
          class="search-input"
          @keyup.enter="fetchButlerList"
        />
        <select
          v-model="statusFilter"
          placeholder="状态筛选"
          class="status-select"
          @change="fetchButlerList"
        >
          <option label="全部" value=""></option>
          <option label="待审核" value="pending"></option>
          <option label="已通过" value="approved"></option>
          <option label="已拒绝" value="rejected"></option>
        </select>
        <button type="primary" @click="fetchButlerList">搜索</button>
      </view>
      <button type="success" @click="openCreateDialog">新增管家</button>
    </view>

    <!-- 管家列表表格 -->
    <uni-table
      :data="butlerList"
      border
      stripe
      style="width: 100%"
      :header-cell-style="{ background: '#f5f7fa', color: '#333', height: '40px' }"
    >
      <uni-tr>
        <uni-th width="80rpx" >ID</uni-th>
        <uni-th class="th2">姓名</uni-th>
        <uni-th width="50rpx">电话</uni-th>
        <uni-th width="80rpx">申请日期</uni-th>
		<uni-th width="40rpx">位置</uni-th>
        <uni-th width="50rpx">状态</uni-th>
        <uni-th class="th7">操作</uni-th>
      </uni-tr>
      <uni-tr v-for="item in butlerList" :key="item._id">
        <uni-td>{{ item._id }}</uni-td>
        <uni-td>{{ item.realName }}</uni-td>
        <uni-td>{{ item.phone }}</uni-td>
        <uni-td>{{ formatDate(item.createTime) }}</uni-td>
        <uni-td>
			<button type="primary" size="mini" @click="getLocation(item.location)">查看</button>
		</uni-td>
        <uni-td>
          <view :class="`status-text status-${item.status}`">
            {{ statusTextMap[item.status] }}
          </view>
        </uni-td>
        <uni-td>
          <view class="operation-btn">
            <button type="default" size="mini" @click="openDetailDialog(item)">查看</button>
            <button type="default" size="mini" @click="openEditDialog(item)">编辑</button>
			<button type="primary" size="mini" @click="setLocation(item)">范围设定</button>
            <button type="warn" style="color: #fff;"  size="mini" class="text-danger" @click="handleDelete(item._id)">冻结</button>
          </view>
        </uni-td>
      </uni-tr>
    </uni-table>

    <!-- 分页组件 -->
    <view class="pagination">
      <uni-pagination
        background
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        :layout="['total', 'sizes', 'prev', 'pager', 'next', 'jumper']"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </view>

    <!-- 详情/编辑/新增弹窗 -->
    <uni-popup ref="formPopup" type="center" :mask-click="true">
      <view class="popup-container">
        <view class="popup-header">
          <text>{{ dialogTitle }}</text>
          <button type="text" class="close-btn" @click="closeFormPopup">✕</button>
        </view>
        <uni-forms
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120rpx"
          class="popup-form"
        >
          <uni-forms-item label="真实姓名" name="realName">
            <input v-model="form.realName" :disabled="dialogType === 'detail'" />
          </uni-forms-item>
          <uni-forms-item label="联系电话" name="phone">
            <input v-model="form.phone" type="number" :disabled="dialogType === 'detail'" />
          </uni-forms-item>
          <uni-forms-item label="服务状态" name="status">
            <select v-model="form.status" :disabled="dialogType === 'detail'">
              <option label="待审核" value="pending"></option>
              <option label="已通过" value="approved"></option>
              <option label="已拒绝" value="rejected"></option>
            </select>
          </uni-forms-item>
           <uni-forms-item label="头像">
            <uni-file-picker
              file-mediatype="image"
              :limit="1"
              :auto-upload="true"
              @success="handleFileUpload('avatar', $event)"
              @delete="handleFileDelete('avatar')"
              dir="/linlier/avatar"
            >
              <view class="upload-preview">
                <image v-if="form.avatar.url" :src="form.avatar.url" mode="aspectFill"></image>
                <view v-else class="upload-placeholder" :disabled="dialogType === 'detail'">
                  <text>点击上传头像</text>
                </view>
              </view>
            </uni-file-picker>
          </uni-forms-item>
          <uni-forms-item label="身份证正面">
            <uni-file-picker
              file-mediatype="image"
              :limit="1"
              :auto-upload="true"
              @success="handleFileUpload('idCard.front', $event)"
              @delete="handleFileDelete('idCard.front')"
              dir="/linlier/idcard"
            >
              <view class="upload-preview">
                <image v-if="form.idCard.front.url" :src="form.idCard.front.url" mode="aspectFill"></image>
                <view v-else class="upload-placeholder" :disabled="dialogType === 'detail'">
                  <text>点击上传身份证正面</text>
                </view>
              </view>
            </uni-file-picker>
          </uni-forms-item>
          <uni-forms-item label="身份证反面">
            <uni-file-picker
              file-mediatype="image"
              :limit="1"
              :auto-upload="true"
              @success="handleFileUpload('idCard.back', $event)"
              @delete="handleFileDelete('idCard.back')"
              dir="/linlier/idcard"
            >
              <view class="upload-preview">
                <image v-if="form.idCard.back.url" :src="form.idCard.back.url" mode="aspectFill"></image>
                <view v-else class="upload-placeholder" :disabled="dialogType === 'detail'">
                  <text>点击上传身份证反面</text>
                </view>
              </view>
            </uni-file-picker>
          </uni-forms-item>
          <uni-forms-item label="自我简介" name="introduction">
            <textarea v-model="form.introduction" rows="3" :disabled="dialogType === 'detail'" />
          </uni-forms-item>
        </uni-forms>
        <view class="popup-footer">
          <button type="default" @click="closeFormPopup">取消</button>
          <button type="primary" @click="handleSave" v-if="dialogType !== 'detail'">保存</button>
        </view>
      </view>
    </uni-popup>

    <!-- 评价列表弹窗 -->
    <uni-popup ref="evalPopup" type="center" :mask-click="false">
      <view class="popup-container eval-popup">
        <view class="popup-header">
          <text>管家评价列表</text>
          <button type="text" class="close-btn" @click="closeEvalPopup">✕</button>
        </view>
        <uni-table :data="currentButlerEvaluations" border stripe>
          <uni-tr>
            <uni-th>评价人</uni-th>
            <uni-th>评价时间</uni-th>
            <uni-th>评分</uni-th>
            <uni-th>评价内容</uni-th>
          </uni-tr>
          <uni-tr v-for="item in currentButlerEvaluations" :key="item._id">
            <uni-td>{{ item.userName }}</uni-td>
            <uni-td>{{ formatDate(item.createTime) }}</uni-td>
            <uni-td>
              <view class="star-rating">
                <text v-for="i in 5" :key="i" class="star" :class="i <= item.score ? 'active' : ''">★</text>
              </view>
            </uni-td>
            <uni-td>{{ item.content }}</uni-td>
          </uni-tr>
        </uni-table>
        <view class="popup-footer">
          <button type="primary" @click="closeEvalPopup">关闭</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import moment from 'moment' // 需安装：npm install moment

const linlier = uniCloud.importObject('linlier')

export default {
  data() {
    return {
      // 列表数据
      butlerList: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      // 搜索筛选
      searchQuery: '',
      statusFilter: '',
      // 状态文本映射（用于表格和表单）
      statusTextMap: {
        pending: '待审核',
        approved: '已通过',
        rejected: '已拒绝'
      },
      // 弹窗状态
      dialogType: 'create', // create/edit/detail
      dialogTitle: '新增管家',
      form: {
        _id: '',
        realName: '',
        phone: '',
        status: 'pending',
        serviceTypes: [],
        avatar: {}, // 头像：{ url: '', fileID: '' }
        idCard: {
          front: {}, // 身份证正面
          back: {} // 身份证反面
        },
        introduction: ''
      },
      // 表单校验规则
      rules: {
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择服务状态', trigger: 'change' }
        ],
        serviceTypes: [
          { required: true, message: '请至少选择一项服务类型', trigger: 'change' }
        ]
      },
      // 评价列表
      currentButlerEvaluations: []
    }
  },
  onLoad() {
    // 页面加载时获取列表数据
    this.fetchButlerList()
  },
  methods: {
    /**
     * 获取管家列表（带搜索、筛选、分页）
     */
    async fetchButlerList() {
		console.log("用户",JSON.stringify(this.$store.state.user) );
      try {
        uni.showLoading({ title: '加载中...' })
        const res = await linlier.getLinliers({userTel:"13665087998"},{
          phone: this.store?.user?.tel || '13665087998', // 从全局状态获取当前用户电话
          realName: this.searchQuery, // 搜索关键词
          status: this.statusFilter, // 状态筛选
          pageSize: this.pageSize,
          currentPage: this.currentPage
        })
        if (res.code === 0) {
          this.butlerList = res.data
          this.total = res.data.length
        } else {
          uni.showToast({ title: res.message || '获取列表失败', icon: 'none' })
        }
      } catch (err) {
        console.error('获取管家列表失败：', err)
        uni.showToast({ title: '网络错误', icon: 'none' })
      } finally {
        uni.hideLoading()
      }
    },

    /**
     * 打开新增弹窗
     */
    openCreateDialog() {
      this.dialogType = 'create'
      this.dialogTitle = '新增管家'
      this.resetForm() // 重置表单
      this.$refs.formPopup.open()
    },

    /**
     * 打开编辑弹窗
     * @param {Object} item - 管家数据
     */
    openEditDialog(item) {
      this.dialogType = 'edit'
      this.dialogTitle = '编辑管家'
      // 深拷贝数据到表单（避免直接修改列表数据）
      this.form = JSON.parse(JSON.stringify(item))
      this.$refs.formPopup.open()
    },
     getLocation(location){
		 console.log(JSON.stringify(location));
		 const {latitude,longitude}=location
		uni.openLocation({
			latitude:latitude,
			longitude:longitude,
			scale:16,
			success(e) {
				console.log('成功回调',e);
			}
		
		}) 
	 },
	 setLocation(linlier){
         const formated=encodeURIComponent(JSON.stringify(linlier)) 
		uni.navigateTo({
			url:`../../own/map/map?data=${formated}`
		}) 
	 },
    /**
     * 打开详情弹窗
     * @param {Object} item - 管家数据
     */
    async openDetailDialog(item) {
      this.dialogType = 'detail'
      this.dialogTitle = '查看管家'
  
         const res = this.butlerList.find(u=>u._id===item._id)
          this.form = res
          this.currentButlerEvaluations = res.evaluations || []
          this.$refs.formPopup.open()
     },

    /**
     * 关闭表单弹窗
     */
    closeFormPopup() {
      this.$refs.formPopup.close()
      // 重置表单校验状态
      this.$nextTick(() => {
        this.$refs.formRef?.clearValidate()
      })
    },

    /**
     * 打开评价弹窗
     * @param {Object} item - 管家数据
     */
    async openEvalDialog(item) {
      try {
        uni.showLoading({ title: '加载评价...' })
        const res = await linlier.getLinlierEvaluations({ butlerId: item._id })
        if (res.code === 0) {
          this.currentButlerEvaluations = res.data
          this.$refs.evalPopup.open()
        } else {
          uni.showToast({ title: res.message || '获取评价失败', icon: 'none' })
        }
      } catch (err) {
        console.error('获取评价失败：', err)
        uni.showToast({ title: '网络错误', icon: 'none' })
      } finally {
        uni.hideLoading()
      }
    },

    /**
     * 关闭评价弹窗
     */
    closeEvalPopup() {
      this.$refs.evalPopup.close()
    },

    /**
     * 保存表单数据（新增/编辑）
     */
    async handleSave() {
      // 表单校验
      const valid = await this.$refs.formRef.validate()
      if (!valid) return

      try {
        uni.showLoading({ title: '保存中...' })
        const res = await linlier.saveLinlier(this.form)
        if (res.code === 0) {
          uni.showToast({ title: '保存成功' })
          this.closeFormPopup()
          this.fetchButlerList() // 刷新列表
        } else {
          uni.showToast({ title: res.message || '保存失败', icon: 'none' })
        }
      } catch (err) {
        console.error('保存管家失败：', err)
        uni.showToast({ title: '网络错误', icon: 'none' })
      } finally {
        uni.hideLoading()
      }
    },

    /**
     * 删除管家
     * @param {string} id - 管家ID
     */
    async handleDelete(id) {
      uni.showModal({
        title: '提示',
        content: '此操作将永久删除该管家信息，是否继续？',
        confirmText: '确定',
        cancelText: '取消',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '删除中...' })
              const res = await linlier.deleteLinlier({ _id: id })
              if (res.code === 0) {
                uni.showToast({ title: '删除成功' })
                this.fetchButlerList() // 刷新列表
              } else {
                uni.showToast({ title: res.message || '删除失败', icon: 'none' })
              }
            } catch (err) {
              console.error('删除管家失败：', err)
              uni.showToast({ title: '网络错误', icon: 'none' })
            } finally {
              uni.hideLoading()
            }
          }
        }
      })
    },

    /**
     * 重置表单
     */
    resetForm() {
      this.form = {
        _id: '',
        realName: '',
        phone: '',
        status: 'pending',
        serviceTypes: [],
        avatar: {},
        idCard: { front: {}, back: {} },
        introduction: ''
      }
      // 重置文件选择器（删除已选文件）
      this.$nextTick(() => {
        this.$refs.formRef?.clearValidate()
        // 遍历文件选择器并重置（uni-file-picker 无直接重置方法，需手动清空）
        const filePickers = this.$refs.formRef?.$children?.filter(child => child.$options.name === 'uni-file-picker')
        filePickers?.forEach(picker => {
          picker.files = []
        })
      })
    },

    /**
     * 文件上传回调
     * @param {string} path - 表单字段路径（如 'avatar'、'idCard.front'）
     * @param {Object} res - 上传成功结果
     */
    handleFileUpload(path, res) {
      const fileInfo = res.tempFilePaths[0] // 上传后的文件信息
      // 解析路径并赋值（如 path = 'idCard.front' → form.idCard.front = fileInfo）
      const keys = path.split('.')
      let target = this.form
      keys.forEach((key, index) => {
        if (index === keys.length - 1) {
          target[key] = {
            url: fileInfo.url, // 预览地址
            fileID: fileInfo.fileID // 云存储文件ID（用于后续保存）
          }
        } else {
          target = target[key]
        }
      })
    },

    /**
     * 文件删除回调
     * @param {string} path - 表单字段路径（如 'avatar'、'idCard.front'）
     */
    handleFileDelete(path) {
      // 解析路径并清空
      const keys = path.split('.')
      let target = this.form
      keys.forEach((key, index) => {
        if (index === keys.length - 1) {
          target[key] = {}
        } else {
          target = target[key]
        }
      })
    },

    /**
     * 格式化日期
     * @param {number} timestamp - 时间戳
     * @returns {string} 格式化后的日期字符串
     */
    formatDate(timestamp) {
      return timestamp ? moment(timestamp).format('YYYY-MM-DD HH:mm:ss') : ''
    },

    /**
     * 分页大小改变
     * @param {number} val - 新的每页条数
     */
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1 // 页码重置为1
      this.fetchButlerList()
    },

    /**
     * 当前页码改变
     * @param {number} val - 新的页码
     */
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchButlerList()
    }
  }
}
</script>

<style lang="scss" scoped>
/* 页面容器 */
.admin-container {
  padding: 20rpx;
  background-color: #f9f9f9;
  min-height: 100vh;
}

/* 页面标题 */
.page-header {
  margin-bottom: 20rpx;
}
.page-header text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 操作栏 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  flex-wrap: wrap;
  gap: 10rpx;
}
.search-filter {
  display: flex;
  align-items: center;
  gap: 10rpx;
  flex-wrap: wrap;
}
.search-input, .status-select {
  width: 220rpx;
  height: 60rpx;
  border: 1rpx solid #dcdfe6;
  border-radius: 8rpx;
  padding: 0 15rpx;
}

/* 分页容器 */
.pagination {
  margin-top: 30rpx;
  display: flex;
  justify-content: flex-end;
}

/* 表格操作按钮 */
.operation-btn {
  display: flex;
  gap: 15rpx;
}
.operation-btn button {
  padding: 0 20rpx;
}

.text-danger {
  color: #f56c6c;
}

/* 状态文本样式 */
.status-text {
  padding: 2rpx 10rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}
.status-pending {
  background-color: #fff3cd;
  color: #856404;
}
.status-approved {
  background-color: #d4edda;
  color: #155724;
}
.status-rejected {
  background-color: #f8d7da;
  color: #721c24;
}

/* 弹窗容器 */
.popup-container {
  width: 85%;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}
/* 弹窗头部 */
.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}
.popup-header text {
  font-size: 30rpx;
  font-weight: bold;
}
.close-btn {
  font-size: 40rpx;
  color: #999;
  padding: 0;
  height: auto;
  line-height: 1;
}
/* 弹窗表单 */
.popup-form {
  padding: 30rpx;
  max-height: 70vh;
  overflow-y: auto;
}
/* 弹窗底部 */
.popup-footer {
  display: flex;
  justify-content: flex-end;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
  gap: 15rpx;
}

/* 上传预览样式 */
.upload-preview {
  width: 100%;
  height: 200rpx;
  border: 1rpx dashed #dcdfe6;
  border-radius: 8rpx;
  position: relative;
  overflow: hidden;
}
.upload-preview image {
  width: 100%;
  height: 100%;
}
.upload-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  color: #999;
  font-size: 24rpx;
}
.upload-placeholder text {
  margin-top: 10rpx;
}

/* 评价弹窗 */
.eval-popup {
  width: 90%;
  max-width: 700rpx;
}
.eval-popup .uni-table {
  max-height: 60vh;
  overflow-y: auto;
}

/* 星级评分 */
.star-rating {
  color: #ccc;
  font-size: 28rpx;
}
.star-rating .star.active {
  color: #ffd700;
}
</style>